<template>
    <div class="bc-container">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/DueDiligence' }">企业尽职调查</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/DDReportType' }">选择报告类型</el-breadcrumb-item>
            <el-breadcrumb-item class="bc-item">报告预览</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div class="ddrt-container">
        <div class="ddrt-header">
            <h3>选择报告类型</h3>
            <p>多维度数据分析全面评估企业风险与价值</p>
        </div>
        <div class="ddrtc-container">
            <div class="ddrt-list">
                <div class="item" :class="{ 'active': index + 1 == permissonPDF }"
                    v-for="(item, index) in reportTypeData" :key="index" @click="onExample(item.id)">
                    <div class="img">
                        <img :src="item.icon" alt="">
                    </div>
                    <div class="desc">
                        <h3>{{ item.title }}</h3>
                        <p>{{ item.desc }}</p>
                        <div class="btns">
                            <el-button @click="onExample(item.id)">查看样例</el-button>
                            <el-button type="primary" @click.stop="onPreView(item.id)">报告预览</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="pdf-report">
                <el-scrollbar ref="scrollbarRef" height="100%">
                    <vue-pdf-embed @loaded="onLoaded" :source="pdfState.url" v-for="page in pdfState.numPages"
                        :page="page" :key="page" textLayer ref="vuePdfRef" />
                </el-scrollbar>
                <div class="btns">
                    <el-button>关闭预览</el-button>
                    <el-button type="primary" @click="onPDFDownload">导出报告</el-button>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue"
import { useRoute, useRouter } from "vue-router"
import l1 from "../../assets/images/DueDiligence/l1.png"
import l2 from "../../assets/images/DueDiligence/l2.png"
import l3 from "../../assets/images/DueDiligence/l3.png"
import l4 from "../../assets/images/DueDiligence/l4.png"
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { getSCAuth, setSCAuth, removeSCAuth } from '@/utils/auth'
// 引入PDF
import VuePdfEmbed from "vue-pdf-embed";
import { createLoadingTask } from "vue3-pdfjs/esm";

import { getInvestReport, getInvestReportPDF, getFinancialReport, getFinancialReportPDF, getSellerChainReport, getSellerChainReportPDF, getSellerChainAuth } from "../../api/DueDiligence"
import { useDueDiligenceStore } from "../../stores/modules/DueDiligence"
import { useAuthStore } from "../../stores/modules/Auth"
import tip from "../../assets/pdf/tip.pdf"
import { polling, clearPolling } from "../../utils/polling"

const route = useRoute()
const router = useRouter()
const dueDiligenceStore = useDueDiligenceStore()
const authStore = useAuthStore()
const channel = ref("")

// 权限
const permissonPDF = ref(0)
const scrollbarRef = ref(null)
// 默认点哪里进入的: 查看样例/预览报告
const entryType = ref('example')
let loading = null

const vuePdfRef = ref(null);
const pdfState = reactive({
    url: tip,
    // url: pdfUrl,
    // 当前页
    pageNum: 0,
    // 总页数
    numPages: 1,
})

const onLoaded = () => {
    loading.close()
}

/**
 * 获取状态
 */
onMounted(() => {
    if (router.currentRoute.value.query.message) {
        channel.value = router.currentRoute.value.query.message
    }
})

onMounted(() => {
    /**
     * 等待加载PDF
     */
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    entryType.value = route.params.type
    permissonPDF.value = Number(route.params.id)
    loadingPDF(permissonPDF.value)
})

/**
 * 加载对应PDF
 */
const loadingPDF = (id) => {
    if (entryType.value == 'preview') {
        switch (id) {
            case 1:
                pdfState.url = tip
                httpInvestReportPDF(dueDiligenceStore.companyName, dueDiligenceStore.keyNo, '北京中研硕福科技有限公司')
                break;
            case 2:
                pdfState.url = tip
                httpFinancialPDF(dueDiligenceStore.companyName, dueDiligenceStore.keyNo, '北京中研硕福科技有限公司')
                break;
            case 3:
                pdfState.url = tip
                break;
            case 4:
                pdfState.url = tip
                loadingAuthPDF()
                break;
        }
    } else {
        switch (id) {
            case 1:
                pdfState.url = 'https://store.industrychain.online/zhaoshang/%E6%8B%9B%E5%95%86%E5%87%86%E5%85%A5%E5%88%86%E6%9E%90%E6%8A%A5%E5%91%8A%E6%A0%B7%E4%BE%8B_20240522160412.pdf'
                pdfTotals()
                break;
            case 2:
                pdfState.url = 'https://store.industrychain.online/zhaoshang/%E4%BC%81%E4%B8%9A%E8%B4%A2%E5%8A%A1%E5%88%86%E6%9E%90%E6%8A%A5%E5%91%8A%E6%A0%B7%E4%BE%8B_20240522160412.pdf'
                pdfTotals()
                break;
            case 3:
                pdfState.url = 'https://store.industrychain.online/zhaoshang/%E4%BC%81%E4%B8%9A%E7%94%B5%E5%8A%9B%E5%88%86%E6%9E%90%E6%8A%A5%E5%91%8A%E6%A0%B7%E4%BE%8B_20240522160413.pdf'
                pdfTotals()
                break;
            case 4:
                pdfState.url = 'https://store.industrychain.online/zhaoshang/%E4%BC%81%E4%B8%9A%E4%BE%9B%E5%BA%94%E9%93%BE%E5%88%86%E6%9E%90%E6%8A%A5%E5%91%8A%E6%A0%B7%E4%BE%8B_20240522160415.pdf'
                pdfTotals()
                break;
        }
    }
}

const pdfTotals = (url) => {
    const loadingTask = createLoadingTask(pdfState.url);
    loadingTask.promise.then((pdf) => {
        // 获取页面总页数
        pdfState.numPages = pdf.numPages
    });
    // 切换pdf回到顶部
    scrollbarRef.value.setScrollTop(0)
}

onMounted(() => {
    pdfTotals()
});


function getPDFFileName() {
    const last_index = pdfState.url.lastIndexOf('/');
    return pdfState.url.slice(last_index + 1);
}

const httpInvestReport = (companyName, keyNo, client) => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    getInvestReport({
        name: companyName, //被调公司名称
        keyNo: keyNo,  //被调公司社会信用代码
        client: client //调查方
    }).then(res => {
        loading.close()
        window.location.href = res.msg
    }).catch(error => {
        console.log(error);
        loading.close()
        ElMessage({ message: "报告暂时无法生成,请稍后再试!", type: 'error', duration: 5 * 1000 })
    })
}

const httpInvestReportPDF = (companyName, keyNo, client) => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    getInvestReport({
        name: companyName, //被调公司名称
        keyNo: keyNo,  //被调公司社会信用代码
        client: client //调查方
    }).then(res => {
        getInvestReportPDF({
            name: companyName, //被调公司名称
            keyNo: keyNo,  //被调公司社会信用代码
            client: client //调查方
        }).then(res => {
            loading.close()
            pdfState.url = res.msg
            pdfTotals()
        }).catch(error => {
            loading.close()
            ElMessage({ message: "报告暂时无法生成,请稍后再试!", type: 'error', duration: 5 * 1000 })
        })
    }).catch(error => {
        loading.close()
        ElMessage({ message: "报告暂时无法生成,请稍后再试!", type: 'error', duration: 5 * 1000 })
    })
}

const httpFinancial = (companyName, keyNo, client) => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    getFinancialReport({
        name: companyName, //被调公司名称
        keyNo: keyNo,  //被调公司社会信用代码
        client: client //调查方
    }).then(res => {
        loading.close()
        window.location.href = res.msg
    }).catch(error => {
        loading.close()
        ElMessage({ message: "报告暂时无法生成,请稍后再试!", type: 'error', duration: 5 * 1000 })
    })
}

const httpFinancialPDF = (companyName, keyNo, client) => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    getFinancialReport({
        name: companyName, //被调公司名称
        keyNo: keyNo,  //被调公司社会信用代码
        client: client //调查方
    }).then(res => {
        getFinancialReportPDF({
            name: companyName, //被调公司名称
            keyNo: keyNo,  //被调公司社会信用代码
            client: client //调查方
        }).then(res => {
            loading.close()
            pdfState.url = res.msg
            pdfTotals()
        }).catch(error => {
            loading.close()
            ElMessage({ message: "报告暂时无法生成,请稍后再试!", type: 'error', duration: 5 * 1000 })
        })
    }).catch(error => {
        loading.close()
        ElMessage({ message: "报告暂时无法生成,请稍后再试!", type: 'error', duration: 5 * 1000 })
    })
}


const httpSellerChain = (authKey, entCreditCode) => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    getSellerChainReport({
        authKey: authKey,
        entCreditCode: entCreditCode,
    }).then(res => {
        loading.close()
        window.location.href = res.msg
    }).catch(error => {
        loading.close()
        ElMessage({ message: "报告暂时无法生成,请稍后再试!", type: 'error', duration: 5 * 1000 })
    })
}

const httpSellerChainPDF = (authKey, entCreditCode) => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    getSellerChainReport({
        authKey: authKey,
        entCreditCode: entCreditCode,
    }).then(res => {
        getSellerChainReportPDF({
            authKey: authKey,
            entCreditCode: entCreditCode,
        }).then(res => {
            loading.close()
            pdfState.url = res.msg
            pdfTotals()
        }).catch(error => {
            loading.close()
            ElMessage({ message: "报告暂时无法生成,请稍后再试!", type: 'error', duration: 5 * 1000 })
        })
    }).catch(error => {
        loading.close()
        ElMessage({ message: "报告暂时无法生成,请稍后再试!", type: 'error', duration: 5 * 1000 })
    })
}


const loadingAuthPDF = () => {
    /**
     * 判断是否授权过
     */
    if (!getSCAuth("SCAuthStatus")) {
        getSellerChainAuth({ creditCode: dueDiligenceStore.keyNo }).then(res => {
            setSCAuth("SCAuthStatus", "true", 1)
        }).catch(error => {
            setSCAuth("SCAuthStatus", "true", 1)
            router.push("/SCAuth")
        })
    } else {
        /**
         * 轮询获取授权结果
         */
        polling(getSellerChainAuth, { authKey: authStore.authKey }, 10000).then(res => {
            httpSellerChainPDF(authStore.authKey, dueDiligenceStore.keyNo)
        })
    }
}

/**
 * 预览报告
 */
const onPreView = (id) => {
    permissonPDF.value = id
    entryType.value = "preview"
    if (id === 1) {
        loadingPDF(id)
    }
    if (id === 2) {
        loadingPDF(id)
    }
    if (id === 3) {
        router.push("/ElectroAuth")
        return;
    }
    if (id === 4) {
        loadingAuthPDF()
    }
}

/**
 * 查看样例
 */
const onExample = (id) => {
    permissonPDF.value = id
    entryType.value = "example"
    loadingPDF(id)
}

/**
 * 导出报告
 */
const onPDFDownload = () => {
    if (permissonPDF.value == 1) {
        httpInvestReport(dueDiligenceStore.companyName, dueDiligenceStore.keyNo, '北京中研硕福科技有限公司')
    } else if (permissonPDF.value == 2) {
        httpFinancial(dueDiligenceStore.companyName, dueDiligenceStore.keyNo, '北京中研硕福科技有限公司')
    } else if (permissonPDF.value == 3) {
        router.push("/ElectroAuth")
        return;
    } else if (permissonPDF.value == 4) {
        if (getSCAuth("SCAuthStatus")) {
            getSellerChainAuth({
                authKey: authStore.authKey
            }).then(res => {
                httpSellerChain(authStore.authKey, dueDiligenceStore.keyNo)
            }).catch(err => {
                ElMessageBox.alert('授权过程需要等待几分钟哦~~', '温馨提示', {
                    confirmButtonText: '知晓',
                    callback: (action) => {
                        ElMessage({
                            type: 'success',
                            message: '感谢您的理解',
                        })
                    },
                })
            })
        } else {
            router.push("/SCAuth")
        }
    }
}


const reportTypeData = [
    {
        id: 1,
        title: "招商准入分析报告",
        desc: "企业无感调查，根据企业工商注册、股权投资、 司法涉诉、知识产权、社保招聘等信息，对企 业进行准入分析",
        icon: l1
    },
    {
        id: 2,
        title: "企业财务分析报告",
        desc: "企业无感调查，根据企业资产负债、所有者权 益、收入、利润、纳税等信息，全面深入了解 企业经营状况",
        icon: l2
    },
    {
        id: 3,
        title: "企业用电分析报告",
        desc: "企业授权调查，根据企业的用电电费、电量、 用电行为等信息，进行企业的经营情况分析， 适用于有独立电表的直供电企业",
        icon: l3
    },
    {
        id: 4,
        title: "企业供应链分析报告",
        desc: "企业授权调查，综合企业的上游供应商、下游 客户、采购及销售商品交易等信息，多维度了 解企业供应链上下游情况",
        icon: l4
    }
]

onUnmounted(() => {
    clearPolling()
    loading.close()
})

</script>
<style lang="less" scoped>
.ddrt-container {
    background: #fff;
    padding: 20px 50px;
    padding-bottom: 60px;

    .ddrt-header {
        h3 {
            font-size: 25px;
            color: #373737;
        }

        p {
            font-size: 16px;
            color: #000000;
            margin-top: 10px;
        }
    }

    .ddrtc-container {
        display: flex;

        .ddrt-list {
            flex: 1;
            overflow: hidden;
            clear: both;
            padding: 10px;
            margin-right: 50px;


            .item {
                margin: 10px 0;
                margin-right: 50px;
                box-shadow: -1px -1px 15px rgba(0, 0, 0, .1);
                background: linear-gradient(#f0f4fc, #ffffff);
                padding: 15px;
                display: flex;
                border-radius: 10px;
                border: 2px solid #ffffff;
                cursor: pointer;

                .img {
                    img {
                        width: 100px;
                        height: 130px;
                    }
                }

                .desc {
                    padding: 0 20px;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;

                    h3 {
                        font-size: 20px;
                    }

                    p {
                        font-size: 16px;
                    }

                    .btns {
                        display: flex;
                        justify-content: flex-end;
                    }
                }
            }

            .item.active {
                border: 2px solid #496bff;

            }
        }

        .pdf-report {
            flex: 1;
            padding: 10px;
            box-shadow: -1px -1px 15px rgba(0, 0, 0, .1);
            background: linear-gradient(#f0f4fc, #ffffff);

            :deep(.el-scrollbar) {
                height: 650px;
            }

            .btns {
                margin-top: 10px;
                display: flex;
                justify-content: space-evenly;
            }
        }
    }
}
</style>
